package cn.iocoder.yudao.module.trade.service.ordersafetychecktemplate;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.CollectionUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.infra.api.code.AutoCodeUtilsApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.trade.controller.admin.order.vo.TradeOrderBaseVO;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetycheck.vo.OrderSafetyCheckSaveReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetycheckitemrelation.vo.OrderSafetyCheckItemRelationRespVO;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetychecktemplate.vo.OrderSafetyCheckTemplatePageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetychecktemplate.vo.OrderSafetyCheckTemplateRespVO;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetychecktemplate.vo.OrderSafetyCheckTemplateSaveReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetychecktemplateitem.vo.OrderSafetyCheckTemplateItemRespVO;
import cn.iocoder.yudao.module.trade.controller.admin.ordersafetycheckterm.vo.OrderSafetyCheckTermRespVO;
import cn.iocoder.yudao.module.trade.convert.ordersafetycheckTemplate.OrderSafetyCheckConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.ordersafetycheck.OrderSafetyCheckDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.ordersafetychecktemplate.OrderSafetyCheckTemplateDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.ordersafetychecktemplateitem.OrderSafetyCheckTemplateItemDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.ordersafetycheckterm.OrderSafetyCheckTermDO;
import cn.iocoder.yudao.module.trade.dal.mysql.ordersafetycheck.OrderSafetyCheckMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.ordersafetychecktemplate.OrderSafetyCheckTemplateMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.ordersafetychecktemplateitem.OrderSafetyCheckTemplateItemMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.ordersafetycheckterm.OrderSafetyCheckTermMapper;
import cn.iocoder.yudao.module.trade.service.ordersafetycheck.OrderSafetyCheckService;
import cn.iocoder.yudao.module.trade.service.ordersafetychecktemplateitem.OrderSafetyCheckTemplateItemService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.ORDER_SAFETY_CHECK_TEMPLATE_NOT_EXISTS;

/**
 * 安全检查服务 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class OrderSafetyCheckTemplateServiceImpl implements OrderSafetyCheckTemplateService {

    @Resource
    private OrderSafetyCheckTemplateMapper orderSafetyCheckTemplateMapper;

    @Resource
    private OrderSafetyCheckTemplateItemService orderSafetyCheckTemplateItemService;

    @Resource
    private OrderSafetyCheckTemplateItemMapper orderSafetyCheckTemplateItemMapper;

    @Resource
    private OrderSafetyCheckService orderSafetyCheckService;

    @Resource
    private AutoCodeUtilsApi autoCodeUtilsApi;

    @Resource
    private OrderSafetyCheckTermMapper orderSafetyCheckTermMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private OrderSafetyCheckMapper orderSafetyCheckMapper;

    @Override
    public Long createOrderSafetyCheckTemplate(OrderSafetyCheckTemplateSaveReqVO createReqVO) {
        // 插入
        OrderSafetyCheckTemplateDO orderSafetyCheckTemplate = BeanUtils.toBean(createReqVO, OrderSafetyCheckTemplateDO.class);
        orderSafetyCheckTemplateMapper.insert(orderSafetyCheckTemplate);
        // 返回
        return orderSafetyCheckTemplate.getId();
    }

    @Override
    public void updateOrderSafetyCheckTemplate(OrderSafetyCheckTemplateSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderSafetyCheckTemplateExists(updateReqVO.getId());
        // 更新
        OrderSafetyCheckTemplateDO updateObj = BeanUtils.toBean(updateReqVO, OrderSafetyCheckTemplateDO.class);
        orderSafetyCheckTemplateMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderSafetyCheckTemplate(Long id) {
        // 校验存在
        validateOrderSafetyCheckTemplateExists(id);
        // 删除
        orderSafetyCheckTemplateMapper.deleteById(id);
    }

    private void validateOrderSafetyCheckTemplateExists(Long id) {
        if (orderSafetyCheckTemplateMapper.selectById(id) == null) {
            throw exception(ORDER_SAFETY_CHECK_TEMPLATE_NOT_EXISTS);
        }
    }

    @Override
    public OrderSafetyCheckTemplateDO getOrderSafetyCheckTemplate(Long id) {
        return orderSafetyCheckTemplateMapper.selectById(id);
    }

    @Override
    public PageResult<OrderSafetyCheckTemplateRespVO> getOrderSafetyCheckTemplatePage(OrderSafetyCheckTemplatePageReqVO pageReqVO) {
        PageResult<OrderSafetyCheckTemplateRespVO> pageResult = OrderSafetyCheckConvert.INSTANCE.convertPag(orderSafetyCheckTemplateMapper.selectPage(pageReqVO));
        if(null != pageResult && CollUtil.isNotEmpty(pageResult.getList())){
            //排除类型为0的数据
            Iterator<OrderSafetyCheckTemplateRespVO> iterator=  pageResult.getList().iterator();
            if(iterator.hasNext() && iterator.next().getGasUserType().equals(-1)){
                iterator.remove();
            }

            //查询检查项
            pageResult.getList().forEach(orderSafetyCheckTemplateRespVO -> {
                List<OrderSafetyCheckTemplateItemDO>  orderSafetyCheckTemplateItemDOS = orderSafetyCheckTemplateItemService.getOrderSafetyCheckTemplateItemByTemplateId(orderSafetyCheckTemplateRespVO.getId());
                orderSafetyCheckTemplateRespVO.setItems(orderSafetyCheckTemplateItemDOS.size());
            });
        }
        return pageResult;
    }

    @Override
    public List<OrderSafetyCheckTemplateRespVO> getOrderSafetyCheckTemplateList(OrderSafetyCheckTemplatePageReqVO pageReqVO) {
        return OrderSafetyCheckConvert.INSTANCE.convertList(orderSafetyCheckTemplateMapper.selectList(OrderSafetyCheckTemplateDO::getGasUserType,-1));
    }

    @Override
    public List<OrderSafetyCheckTemplateRespVO> getOrderSafetyCheckTemplateSelectList(OrderSafetyCheckTemplatePageReqVO pageReqVO) {
        LambdaQueryWrapperX<OrderSafetyCheckTemplateDO> wrapperX = new LambdaQueryWrapperX<>();
        wrapperX.neIfPresent(OrderSafetyCheckTemplateDO::getGasUserType, -1);
        List<OrderSafetyCheckTemplateRespVO> list = BeanUtils.toBean(orderSafetyCheckTemplateMapper.selectList(wrapperX), OrderSafetyCheckTemplateRespVO.class);
        list.forEach(x -> {
            x.setTermSaveReqVOList(new ArrayList<>());
            List<OrderSafetyCheckTemplateItemDO>  orderSafetyCheckTemplateItemDOS = orderSafetyCheckTemplateItemService.getOrderSafetyCheckTemplateItemByTemplateId(x.getId());
            if (CollectionUtil.isEmpty(orderSafetyCheckTemplateItemDOS)) {
                x.setItemRespVOList(new ArrayList<>());
                return;
            }
            List<OrderSafetyCheckTemplateItemRespVO> respVOList = BeanUtils.toBean(orderSafetyCheckTemplateItemDOS, OrderSafetyCheckTemplateItemRespVO.class);
            respVOList.forEach(resp -> {
                resp.setName(resp.getTitle());
            });
            x.setItemRespVOList(respVOList);
        });
        return list;
    }

    /**
     *  确认订单后 新增安检单
     * @param order
     * @param type
     */
    @Override
    public void createCheckTemplate(TradeOrderBaseVO order, Integer type) {


        List<OrderSafetyCheckTemplateDO> templateDOS = orderSafetyCheckTemplateMapper.selectList();

        Long id = templateDOS.stream().filter(x -> Objects.equals(x.getGasUserType(), type)).findFirst().get().getId();
        // 查询模板对应安检项 （问题标题）
        LambdaQueryWrapperX<OrderSafetyCheckTemplateItemDO> wrapperX = new LambdaQueryWrapperX<>();
        wrapperX.eqIfPresent(OrderSafetyCheckTemplateItemDO::getTemplateId, id);
        List<OrderSafetyCheckTemplateItemDO> itemDOList = orderSafetyCheckTemplateItemMapper.selectList(wrapperX);

        // 组装安检单数据
        OrderSafetyCheckSaveReqVO checkSaveReqVO = new OrderSafetyCheckSaveReqVO();
        checkSaveReqVO.setCode("A" + autoCodeUtilsApi.autoCode("check_order", autoCodeUtilsApi.timeCode()));
        checkSaveReqVO.setCrmId(order.getMemberUserGasId());
        checkSaveReqVO.setOrderId(order.getId());
        checkSaveReqVO.setOrderNo(order.getNo());
        checkSaveReqVO.setCreateName(adminUserApi.getUser(SecurityFrameworkUtils.getLoginUserId()).getUsername());
        List<OrderSafetyCheckItemRelationRespVO> respVOList = new ArrayList<>();
        itemDOList.forEach(x -> {
            LambdaQueryWrapperX<OrderSafetyCheckTermDO> queryWrapperX = new LambdaQueryWrapperX<>();
            queryWrapperX.eq(OrderSafetyCheckTermDO::getItemId, x.getId());
            List<OrderSafetyCheckTermDO> termDOList = orderSafetyCheckTermMapper.selectList(queryWrapperX);
            termDOList.forEach(y -> {
                OrderSafetyCheckItemRelationRespVO respVO = new OrderSafetyCheckItemRelationRespVO();
                respVO.setChenkItemTremId(y.getId());
                respVO.setCheckItemType(y.getType());
                respVO.setContent(y.getContent());
                respVO.setOptions(y.getSelected());
                respVO.setCheckItemId(x.getId());
                respVOList.add(respVO);
            });
        });
        orderSafetyCheckService.createOrderSafetyCheck(checkSaveReqVO.setRelationRespVOList(respVOList));
    }

    @Override
    public void checkTypeTemplate(TradeOrderBaseVO toBean, Integer type) {
        LambdaQueryWrapperX<OrderSafetyCheckDO> wrapperX = new LambdaQueryWrapperX<>();
        wrapperX.eqIfPresent(OrderSafetyCheckDO::getCrmId, toBean.getMemberUserGasId())
                .orderByDesc(OrderSafetyCheckDO::getId);
        List<OrderSafetyCheckDO> checkDOList = orderSafetyCheckMapper.selectList(wrapperX);
        // 如果没有新增过安检单 则直接创建安检单
        if (CollectionUtil.isEmpty(checkDOList)) {
            this.createCheckTemplate(toBean, type);
            return;
        }

        // 取最近一条安检单 如果没有安检则需新增一条安检单
        LocalDateTime checkTime = checkDOList.get(0).getCheckTime();
        if (checkTime == null) {
            this.createCheckTemplate(toBean, type);
            return;
        }
        // 取最近一条安检单 有安检时间则需要校验对应模板安检时间是否过期
        List<OrderSafetyCheckTemplateDO> templateDOS = orderSafetyCheckTemplateMapper.selectList();
        String expirationDate = templateDOS.stream().filter(x -> Objects.equals(x.getGasUserType(), type)).findFirst().get().getExpirationDate();

        LocalDateTime minus = checkTime.plusDays(Long.parseLong(expirationDate));

        LocalDateTime now = LocalDateTime.now();

        // 如果没有超过当前时间则不需要新增安检单
        boolean before = now.isBefore(minus);
        if (before) {
            // 不在安检时间范围内需新增安检单
            this.createCheckTemplate(toBean, type);
        }

    }
}